import axios from 'axios'
import { get as _get } from 'lodash-es'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'

export const CODE_MAP = {
  SUCCESS: '200',
  ERROR: '500',
  NO_AUTH: '403',
  ERR_AUTH: '1001',
  NO_LOGIN: [4210, 4211]
}

const instance = axios.create({
  baseURL: window.$app.ecoGateway,
  timeout: 600000
})

instance.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      throw new Error('http请求出错')
    }
    const res = response.data
    if (CODE_MAP.NO_LOGIN.includes(res?.serverResult?.resultCode)) {
      window.$app.delAuth(true)
      return res
    } else {
      return res
    }
  },
  (err) => {
    console.log(err)
    if (err?.response?.status !== 200) {
      if (CODE_MAP.NO_LOGIN.includes(err?.response?.data?.resultCode)) {
        window.$app.delAuth()
        ElMessage.error('请重新登录！')
        window.$app.delAuth(true)
      } else {
        console.log('出错啦，请联系管理员处理！')
        // ElMessage.error('出错啦，请联系管理员处理！')
      }
      return Promise.reject(err.response.data)
    } else if (err.response.data) {
      return Promise.reject(err.response.data)
    } else {
      throw new Error(err)
    }
  }
)

instance.interceptors.request.use((config) => {
  if (window.$app.user && window.$app.user.token) {
    if (!config.headers) {
      config.headers = {}
    }
    config.headers = {
      'X-Client-Id': window.$app.appId,
      'Branch_Code': window.$app.user.branchCode,
      'Tenant-Id': window.$app.user.branchCode,
      'Access-Token': window.$app.user.token,
      'Token': window.$app.user.token,
      'X-User-Account': window.$app.user.userId,
      'Current-Org-Id': window.$app.user.orgId,
      'Role-Id': window.$app.user.role
    }
  }

  return config
})

export default instance
